import json
import requests
from typing import Dict, List, Any


# 定义可用函数
def search_weather(city: str, date: str = "today") -> Dict[str, Any]:
    """
    搜索指定城市和日期的天气
   Args:
       city: 城市名称，如"北京"、"上海"
       date: 日期，格式为YYYY-MM-DD或"today"表示今天

   Returns:
       包含天气信息的字典
   """
    # 调用天气API
    response = requests.get(f'http://weather-api.example.com/api/weather?city={city}&date={date}')
    return response.json()


def search_restaurants(location: str, cuisine: str = None, price_range: str = None) -> Dict[str, Any]:
    """
    搜索指定位置的餐厅
   Args:
       location: 位置，如"北京海淀区"
       cuisine: 菜系，如"川菜"、"粤菜"（可选）
       price_range: 价格范围，如"低于100"、"100-300"、"300以上"（可选）

   Returns:
       包含餐厅信息的字典
   """


    # 构建查询参数
    params = {"location": location}
    if cuisine:
        params["cuisine"] = cuisine
    if price_range:
        params["price_range"] = price_range

    # 调用餐厅API
    response = requests.get('http://restaurant-api.example.com/api/search', params=params)
    return response.json()


# 函数字典，映射函数名称到实际函数
available_functions = {
    "search_weather": search_weather,
    "search_restaurants": search_restaurants
}


# 函数描述，用于AI模型判断应该调用哪个函数
function_descriptions = [
    {
        "name": "search_weather",
        "description": "获取指定城市和日期的天气信息",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "城市名称，如北京、上海"
                },
                "date": {
                    "type": "string",
                    "description": "日期，格式为YYYY-MM-DD或today表示今天"
                }
            },
            "required": ["city"]
        }
    },
    {
        "name": "search_restaurants",
        "description": "搜索指定位置的餐厅",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "位置，如北京海淀区"
                },
                "cuisine": {
                    "type": "string",
                    "description": "菜系，如川菜、粤菜"
                },
                "price_range": {
                    "type": "string",
                    "description": "价格范围，如低于100、100-300、300以上"
                }
            },
            "required": ["location"]
        }
    }
]

# 模拟AI模型做出的Function Call决策
def simulate_ai_function_call(user_message: str) -> Dict[str, Any]:
    """
    模拟AI模型分析用户消息并决定调用哪个函数
   实际应用中，这部分由AI模型完成，此处仅为演示
   """
    if "天气" in user_message or "下雨" in user_message:
        # 提取城市
        city = "北京"  # 简化处理，实际应从消息中提取
        if "明天" in user_message:
            date = "2025-04-06"  # 模拟明天日期
        else:
            date = "today"

        return {
            "function": "search_weather",
            "parameters": {
                "city": city,
                "date": date
            }
        }
    elif "餐厅" in user_message or "吃饭" in user_message:
        # 提取位置和偏好
        location = "北京海淀区"  # 简化处理
        cuisine = "川菜" if "川菜" in user_message else None
        price_range = "100-300"  # 默认中等价位

        return {
            "function": "search_restaurants",
            "parameters": {
                "location": location,
                "cuisine": cuisine,
                "price_range": price_range
            }
        }
    else:
        return None  # 不需要调用函数


# 模拟处理用户消息的过程
def process_user_message(user_message: str) -> str:
    """处理用户消息并返回回复"""
    print(f"用户: {user_message}")


    # 判断是否需要Function Call
    function_call = simulate_ai_function_call(user_message)

    if function_call:
        function_name = function_call["function"]
        parameters = function_call["parameters"]

        print(f"AI决定调用函数: {function_name}")
        print(f"参数: {json.dumps(parameters, ensure_ascii=False)}")

        # 执行Function Call
        if function_name in available_functions:
            function_to_call = available_functions[function_name]
            function_response = function_to_call(**parameters)

            print(f"函数返回结果: {json.dumps(function_response, ensure_ascii=False)}")

            # 根据函数返回结果生成回复（简化处理）
            if function_name == "search_weather":
                return f"{parameters['city']}{'明天' if parameters['date'] != 'today' else '今天'}的天气是{function_response['weather']}，温度范围{function_response['temperature']}，降雨概率{function_response['rain_probability']}。"
            elif function_name == "search_restaurants":
                restaurants = function_response.get("restaurants", [])
                if restaurants:
                    restaurant_names = [r["name"] for r in restaurants[:3]]
                    return f"我为您找到了以下餐厅：{', '.join(restaurant_names)}，它们都在{parameters['location']}{'，提供' + parameters['cuisine'] if parameters['cuisine'] else ''}。"
                else:
                    return f"抱歉，没有找到符合条件的餐厅。"
        else:
            return f"抱歉，我无法处理这个请求，因为函数{function_name}不可用。"
    else:
        # 不需要调用函数，直接回复
        return "我理解你的问题，但不需要调用特定工具来回答。[这里是AI模型生成的直接回复]"


# 测试
test_messages = [
    "北京今天天气怎么样？会下雨吗？",
    "推荐几家海淀区的川菜馆",
    "人工智能的发展历史是怎样的？"
]
for message in test_messages:
    response = process_user_message(message)
    print(f"AI: {response}\n")